using System;
using System.Collections.Specialized;
using HttpQuartz.Server.BgServices.QuartzScheduler;
using HttpQuartz.Server.Models;
using Polly;
using Quartz.Impl;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class QuartzSchedulerServiceCollectionExtensions
    {
        public static IServiceCollection AddQuartzScheduler(this IServiceCollection services)
        {
            //httpfactory
            services.AddHttpClient("polly",
                    (client => { client.DefaultRequestHeaders.Add("x-requested-with", "XMLHttpRequest"); }))
                .AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(new[]
                {
                    TimeSpan.FromSeconds(3),
                    TimeSpan.FromSeconds(5),
                    TimeSpan.FromSeconds(10)
                }));

            //ServerChan
            services.AddHttpClient("sc",
                    (client => { client.BaseAddress = new Uri("https://sc.ftqq.com"); }))
                .AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(new[]
                {
                    TimeSpan.FromSeconds(3),
                    TimeSpan.FromSeconds(5)
                }));

            services.AddSingleton<HttpJob>();
            services.AddSingleton((ServiceProvider) =>
            {
                var appSettings = ServiceProvider.GetService<AppSettings>();

                var nv = new NameValueCollection();
                foreach (var kv in appSettings.Quartz)
                {
                    nv.Add(kv.Key, kv.Value);
                }

                var factory = new StdSchedulerFactory(nv);
                var scheduler = factory.GetScheduler().GetAwaiter().GetResult();
                scheduler.JobFactory = new HttpJobFactory(ServiceProvider);
                // LogProvider.SetCurrentLogProvider(new SerilogLogProvider());
                return scheduler;
            });

            //托管服务
            services.AddHostedService<QuartzSchedulerService>();

            return services;
        }
    }
}